package org.linuxsogood.chapter2.helper;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.linuxsogood.chapter2.utils.PropsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

/**
 * Created by m on 16/3/19.
 */
public class DatabaseHelper {

    private static final QueryRunner QUERY_RUNNER = new QueryRunner();
    private static final ThreadLocal<Connection> CONNECTION_HOLDER = new ThreadLocal<>();

    private static final String CONFIG_FILE_NAME = "config.properties";
    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);

    /**
     * 静态代码块初始化数据库相关配置
     */
    static {
        Properties properties = PropsUtil.loadProps(CONFIG_FILE_NAME);
        DRIVER = properties.getProperty("jdbc.driver");
        URL = properties.getProperty("jdbc.url");
        USERNAME = properties.getProperty("jdbc.username");
        PASSWORD = properties.getProperty("jdbc.password");

        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            //
            LOGGER.error("注册数据库驱动失败.{}",e);
        }
    }

    /**
     * 获取数据库连接
     * @return 返回一个数据库连接
     */
    public static Connection getConnection() {
        Connection conn = CONNECTION_HOLDER.get();
        try {
            if (conn == null) {
                conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            }
        } catch (SQLException e) {
            //
            LOGGER.error("获取数据库连接时异常:{}",e);
        } finally {
            CONNECTION_HOLDER.set(conn);
        }
        return conn;
    }

    public static void closeConnection() {
        Connection connection = CONNECTION_HOLDER.get();
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                //关闭连接异常
            } finally {
                connection = null;
                CONNECTION_HOLDER.remove();
            }
        }
    }

    /**
     * 关闭给定的数据库连接
     * @param connection
     */
    public static void closeConnection(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            //关闭连接时异常
            connection = null;
        }finally {
            //
        }
    }

    /**
     * 查询实体列表
     * @param entityClass
     * @param sql
     * @param <T>
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql) {
        List<T> entityList = null;
        Connection conn = getConnection();
        try {
            entityList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<T>(entityClass));
        } catch (SQLException e) {
            LOGGER.error("query entity list failure.{}",e);
        }finally {
            closeConnection(conn);
        }
        return entityList;
    }

    /**
     * 查询实体列表
     * @param entityClass 要返回的实体
     * @param sql sql语句
     * @param params 参数
     * @param <T> 实体
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
        Connection connection = getConnection();
        List<T> entityList = null;
        try {
            entityList = QUERY_RUNNER.query(connection, sql, new BeanListHandler<T>(entityClass), params);
        } catch (SQLException e) {
            //
        } finally {
            closeConnection(connection);
        }
        return entityList;
    }
}
